define([
  'controllers/common/showModal',
  'text!templates/map/controls/generalInfo_Text.html',
  'text!templates/map/controls/generalInfo_ErrorItem.html',
  'text!templates/map/controls/generalInfo.html',
  'text!templates/map/controls/generalInfo_SubcorridorItem.html',
  'text!templates/map/controls/generalInfo_CorridorItem.html',
  'text!templates/map/controls/generalInfo_CorridorFull.html',
  'text!templates/map/controls/generalInfo_SubcorridorItem_Link.html',
], function (ModalController, TextTemplate, HTMLTemplate_ErrorItem, HTMLTemplate, HTMLSubcorridorItem, HTMLCorridorItem, HTMLCorridorFull, HTMLSubcorridorLink) {

    var view = Backbone.View.extend({
        el: $("#main-content"),
        uploader: undefined,
        currentSubcorridor: undefined,
        currentSortLink: undefined,
        deletedCorridors: [],
        deletedSubcorridors: [],
        layersDictionary: undefined,

        currentShape: undefined,
        contentMode: undefined,
        $infobar: undefined,
        
        render: function () {

            this.deletedCorridors = [];
            this.deletedSubcorridors = [];

            var template = Handlebars.compile(HTMLTemplate);
            var html = template();
            this.$el.html(html);

            this.$infobar = $(".leaflet-infobar");

            //update height
            var h = $("#main-content").height();
            $("#projectmap .generalinfo").height(h - 25);
            $("#projectmap .generalinfo .shapeinfo-container").height(h - 25 - 66);
            this.addHandlers();

            this.layersDictionary = {};

            //addlayerview
        },
        expandControl: function () {
            var $this = $(".leaflet-infobar .generalinfo button[data-rel='toggle']");
            $this.attr("data-expanded", "1");
            $this.find("i").attr("class", "icon-angle-up");
            $this.closest(".leaflet-control").removeClass("contracted");
        },
        contractControl: function () {
            var $this = $(".leaflet-infobar .generalinfo button[data-rel='toggle']");
            $this.attr("data-expanded", "0");
            $this.find("i").attr("class", "icon-angle-down");
            $this.closest(".leaflet-control").addClass("contracted");
        },
        removeView: function () {
            $.contextMenu('destroy', '.giContextMenu');
            this.layersDictionary = null;
        },

        showShapeData: function (shape) {
            this.currentShape = shape; //assign selected shape as current
            this.showSidebarContent(true);
            
            if (shape.options.attrObj && shape.options.attrObj["text"] && shape.options.attrObj["text"]["type"] == "html") {
                this.contentMode = "text";
            } else {
                // to do: agregar mas condiciones dependiendo del tipo de dato asociado a la booble
                this.contentMode = "text";
                if(shape.options.attrObj == undefined)
                        shape.options.attrObj = {};
                shape.options.attrObj["text"] = {
                    value: "", type: "html"
                };
            }

            //var dataType = shape.options.attrObj["boobleType"];
            //dataType ? null : shape.options.attrObj["boobleType"] = dataType = "text";
            // update content title
            this.$infobar.find(".shape-title").text(shape.options.title);            
            this.$infobar.find("button.type_" + this.contentMode).addClass("selected");
            
            //this.contentMode = dataType;

            switch (this.contentMode) {
                case "text":
                    var template = Handlebars.compile(TextTemplate);
                    var html = template();
                    this.$infobar.find(".shapeinfo-content").append(html);
                    var $summernote = this.$infobar.find(".shapeinfo-content .summernote");

                    $summernote.summernote({
                        focus: true,

                        toolbar: [
                            //['style', ['style']], // no style button
                            ['style', ['bold', 'italic', 'underline', 'clear']],
                            ['fontsize', ['fontsize']],
                            ['color', ['color']],
                            ['para', ['ul', 'ol', 'paragraph']],
                            ['height', ['height']],
                            //['insert', ['picture', 'link']], // no insert buttons
                            //['table', ['table']], // no table button
                            //['help', ['help']] //no help button
                        ],
                        oninit: function () {
                            if (shape.options.attrObj["text"]) {
                                $summernote.code(shape.options.attrObj["text"]["value"]);
                            }
                        }
                    });
                    
                    // mostrar dropdown
                    $(".note-editor .note-toolbar >> button").on("click", function (evt) {
                        // to do: desplegar el dropdown perteneciente a este elemento
                        // hacer un ejemplo separado con summernote
                        $(this)
                    });

                    //var edit = function () {
                    //    $('.click2edit').summernote({
                    //        focus: true
                    //    });
                    //};
                    var save = function () {
                        var aHTML = $('.click2edit').code(); //save HTML If you need(aHTML: array).
                        $('.click2edit').destroy();
                    };
                    break;
                case "table":

                    break;
                case "list":

                    break;
                case "image":

                    break;
            }
            //} else {
            //    $infobar.find("button.type_text").addClass("selected");
            //    //$("type_text").addClass("selected");

            //}

        },
        showSidebarContent: function (show) {
            // to do: en caso de que sea false y existan datos sin guardar.. preguntar si quiere guardar
            this.contentMode = undefined;
            this.$infobar.find(".shapeinfo-content").children().remove();
            show ? $(".shapeinfo-container").removeClass("nodisplay") : $(".shapeinfo-container").addClass("nodisplay");
        },
        
        
        //refreshAttributes: function () {

        //    this.mapView.getLayerByEntityId(this.currentShape, "link");

        //    //layer.options.attrObj["boobleType"]
        //    itemGeo.attributes.push({ "key": "radius", "type": "radius", "value": layer.getRadius() });
        //},

        addHandlers: function () {
            var that = this;

            // save
            $(".leaflet-infobar .generalinfo button[data-rel='save']").click(function () {
                $("#projectMapSidebar").trigger("saveProject");
            });

            $(".leaflet-infobar .generalinfo button[data-rel='refresh']").click(function () {
                $("#projectMapSidebar").trigger("refreshProject");
            });

            $(".leaflet-infobar .generalinfo button[data-rel='update_shape']").click(function () {
                $("#projectMapSidebar").trigger("updateShapeContent");
            });

            ////back to projects COMENTADO, NO QUIERO ESTA FUNCIONALIDAD POR AHORA
            //$(".leaflet-infobar .generalinfo button[data-rel='backtoprojects']").click(function () {

            //    $("#projectmap").trigger("isOkToBack", [function (isOK) {

            //        if (isOK) {
            //            $("#projectmap").trigger("setMode", ["free"]);
            //            $("#projectmap").trigger("removeControlsForBuild");
            //            $("#projectMapSidebar").trigger("showFPCases");
            //        }
            //    }]);
            //});

            //evaluate
            // COMENTADO, NO QUIERO ESTA FUNCIONALIDAD POR AHORA
            //$(".leaflet-infobar .generalinfo button[data-rel='evaluate_fpCase']").click(function () {

            //    if ($(".leaflet-infobar .generalinfo button[data-rel='save']").hasClass("btn-red")) {
            //        showMessage(translate("save_changes_then_evaluate"));
            //    }
            //    else {
            //        $("#projectMapSidebar").trigger("evaluateFPCase");
            //    }

            //});

            // Assign demand costs
            $(".leaflet-infobar .generalinfo button[data-rel='assign_demand_costs']").click(function () {

                $("#projectMapSidebar").trigger("assignDemandPerSubcorridor");

            });


            // error list
            $(".leaflet-infobar .errorList ul").on("click", "li a", function () {
                var lat = $(this).attr("data-lat");
                var lng = $(this).attr("data-lng");
                $("#projectmap").trigger("moveMapTo", [lat, lng]);
                $("#projectmap").trigger("showAlertMessage", [lat, lng, $(this).closest("li").find("span").html()]);
                return false;
            });

            // click on left list to show popup
            // Facu: no uso esto por ahora
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("click", ".subcorridorItemContainer li table td", function () {
                var entityId = $(this).attr("data-value");
                var geometryType = ($(this).attr("data-type") == "node" ? 1 : 2);
                $("#projectmap").trigger("showLayerPopup", [entityId, geometryType]);
            });


            // click on subcorridor to expand / contract 
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("click", ".subcorridorItemContainer li a.subcorridor, .subcorridorItemContainer li i.expandor", function () {
                if ($(this).closest("li").hasClass("contracted")) {
                    that.sortSubcorridor($(this).closest("li").attr("data-id"));
                }
                $(this).closest("li").toggleClass("contracted")
            });



            //over link/node to show on map
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("mouseover", ".subcorridorItemContainer li table tr", function () {
                if (!$(this).closest("li").hasClass("selecting")) {
                    var leafletid = $(this).attr("data-leaflet");
                    $("#projectmap").trigger("showLinksOrNode", [leafletid]);
                }
            });
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("mouseout", ".subcorridorItemContainer li table tr", function () {

                if (!$(this).closest("li").hasClass("selecting")) {
                    $("#projectmap").trigger("clearAuxLayer");
                }
            });

            // over subcorridor to show on map
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("mouseover", ".subcorridorItemContainer a.subcorridor", function () {
                if (!$(this).closest("li").hasClass("selecting")) {
                    var arr = that.getLayersFromLi($(this).closest("li"));
                    if (arr && arr.length > 0) {
                        $("#projectmap").trigger("drawAuxLayers", [arr]);
                    }
                }

            });
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("mouseout", ".subcorridorItemContainer a.subcorridor", function () {
                if (!$(this).closest("li").hasClass("selecting")) {
                    $("#projectmap").trigger("clearAuxLayer");
                }
            });




            // SUBCORRIDORS
            //add subcorridor
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("click", "button[data-action='add_subcorridor']", function () {
                var newId = $.uuid();
                var addTo = $(this).closest(".corridorList").attr("data-id");
                that.addSubcorridor({
                    tempId: newId,
                    entityId: -1,
                    name: "(" + translate("new_subcorridor") + ")"
                }, addTo);
                that.editSubCorridor(newId);
            });



            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("click", "button.giContextMenu", function () {
                $(this).contextMenu();
            });


            /*
            $.contextMenu({
                selector: '.giContextMenu',
                callback: function (key, options) {

                    var $li = options.$trigger.closest("li");

                    switch (key) {
                        case "_edit":
                            var id = $li.attr("data-id");
                            that.editSubCorridor(id);
                            break;

                        case "_copy":
                            var $newLi = $li.clone().appendTo($li.closest("ul"));
                            var name = $newLi.find("a.subcorridor").text();
                            $newLi.find("a.subcorridor").text(translate("copy_of") + " " + name);
                            var newId = $.uuid();
                            $newLi.attr("data-id", newId);
                            $newLi.attr("data-entity-id", -1);
                            $newLi.addClass("modified");

                            //duplicate subcorridor data links
                            var arr = that.layersDictionary[$li.attr("data-id")];
                            if (arr) {
                                arr = arr.slice(0); //clone
                                that.layersDictionary[newId] = arr;
                            }
                            that.addSubcorridorSortable();
                            that.editSubCorridor(newId);
                            break;

                        case "_delete":
                            if ($(".leaflet-infobar .generalinfo .corridorList .subcorridorItemContainer li").length == 1) {
                                showMessage(translate("cantnot_remove_last_subcorridor"));
                            }
                            else {

                                (new ModalController()).show({
                                    title: translate("warning"),
                                    text: translate("sure_remove_subcorridor"),
                                    buttons: [
                                        { "title": translate("yes"), "css": "primary", "code": "yes" },
                                        { "title": translate("no"), "code": "no" },
                                    ],
                                    callback: function (code) {
                                        if (code == "yes") {

                                            if ($li.attr("data-entity-id")) {
                                                that.deletedSubcorridors.push($li.attr("data-entity-id"));
                                            }
                                            $li.remove();
                                            $("#projectmap").trigger("changeModeOn");
                                            $("#projectmap").trigger("validateIntegrity");
                                        }
                                    }
                                });
                            }
                            break;

                        case "_info":
                            var entityId = $li.attr("data-entity-id");
                            if (entityId != "-1") {
                                $("#projectMapSidebar").trigger("showSubcorridorForm", [entityId]);
                            }
                            else {
                                showMessage(translate("save_changes_then_put_info"));
                            }
                            break;
                    }


                },
                items: {
                    "_edit": { type: "icon_text", name: translate("edit_subcorridor"), iconClass: "icon-edit" },
                    "_copy": { type: "icon_text", name: translate("copy_subcorridor"), iconClass: "icon-copy" },
                    "_delete": { type: "icon_text", name: translate("remove_subcorridor"), iconClass: "icon-trash" },
                    "_info": { type: "icon_text", name: translate("add_subcorridor_data"), iconClass: "icon-info-sign" }
                }
            });
            */

            // define subcorridor
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("click", "button[data-action='define_subcorridor']", function () {

                if ($(this).closest("li").hasClass("contracted")) {
                    that.sortSubcorridor($(this).closest("li").attr("data-id"));
                    $(this).closest("li").removeClass("contracted");
                }
                var id = $(this).closest("li").attr("data-id");
                $(".leaflet-infobar .generalinfo .subcorridorItemContainer li[data-id!='" + id + "']").removeClass("selecting");

                // show if it is hidden
                if ($(this).closest("li").hasClass("subcorridor_hidden")) {
                    $(this).closest("li").find("button[data-action='hide_subcorridor']").click();
                }

                $(this).closest("li").toggleClass("selecting");

                if ($(this).closest("li").hasClass("selecting")) {
                    that.currentSubcorridor = id;
                    $("#projectmap").trigger("setMode", ["selectLinks"]);
                    var arr = that.getLayersFromLi($(this).closest("li"));
                    if (arr) {
                        $("#projectmap").trigger("drawAuxLayers", [arr]);
                    }
                }
                else {
                    $("#projectmap").trigger("setMode", ["free"]);
                }
            });



            // show/hide subcorridor
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("click", "button[data-action='hide_subcorridor']", function () {

                var arr = that.getLayersFromLi($(this).closest("li"));
                if (arr && arr.length > 0) {
                    if ($(this).closest("li").hasClass("subcorridor_hidden")) {
                        $(this).find("i").attr("class", "icon-eye-open");
                        $(this).closest("li").removeClass("subcorridor_hidden");
                        $("#projectmap").trigger("showLayers", [arr]);
                    } else {
                        $(this).find("i").attr("class", "icon-eye-close");
                        $(this).closest("li").addClass("subcorridor_hidden");
                        $("#projectmap").trigger("hideLayers", [arr]);
                    }
                }

            });







            // ENTER on input textbox
            $(".leaflet-infobar .generalinfo .shapeinfo-container ").on("keypress", ".corridorList ul li input", function (e) {
                if (e.which == 13) {
                    $(this).closest(".editor").find("button").first().trigger("click");
                }
            });

            // OK on edit subcorridor
            $(".leaflet-infobar .generalinfo .shapeinfo-container ").on("click", ".corridorList ul li .editor button", function () {
                if ($(this).attr("data-action") == "ok") {
                    var text = $(this).closest(".editor").find("input").val()
                    $(this).closest("li").find("a").html(text);
                    $(this).closest("li").addClass("modified");
                    $("#projectmap").trigger("changeModeOn");
                }
                that.clearEditSubcorridor();
            });



            // CORRIDORS
            //add corridor
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("click", "button[data-action='add_corridor']", function () {
                var newId = $.uuid();
                that.addCorridor({
                    tempId: newId,
                    name: "(" + translate("new_corridor") + ")",
                    entityId: -1
                });
                that.editCorridor(newId);
            });

            // edit corridor
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("click", "button[data-action='edit_corridor']", function () {
                var id = $(this).closest(".corridorList").attr("data-id");
                that.editCorridor(id);
            });

            // delete corridor
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("click", "button[data-action='remove_corridor']", function () {
                var thisId = $(this).closest(".corridorList").attr("data-id");

                if ($(".leaflet-infobar .generalinfo .corridorList").length == 1) {
                    showMessage(translate("cantnot_remove_last_corridor"));
                }
                else if ($(".leaflet-infobar .generalinfo .corridorList[data-id!='" + thisId + "'] .subcorridorItemContainer li").length == 0) {
                    showMessage(translate("cantnot_remove_last_subcorridor"));
                }
                else {

                    var $corridorList = $(this).closest(".corridorList");
                    (new ModalController()).show({
                        title: translate("warning"),
                        text: translate("sure_remove_corridor"),
                        buttons: [
                            { "title": translate("yes"), "css": "primary", "code": "yes" },
                            { "title": translate("no"), "code": "no" },
                        ],
                        callback: function (code) {
                            if (code == "yes") {

                                if ($corridorList.attr("data-entity-id")) {
                                    that.deletedCorridors.push($corridorList.attr("data-entity-id"));
                                }

                                $corridorList.remove();
                                $("#projectmap").trigger("changeModeOn");
                                $("#projectmap").trigger("validateIntegrity");
                            }
                        }
                    });


                }

            });


            // ENTER on input textbox
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("keypress", ".corridorList .corridorEditor input", function (e) {
                if (e.which == 13) {
                    $(this).closest(".editor").find("button").first().trigger("click");
                }
            });

            // OK in edit corridor
            $(".leaflet-infobar .generalinfo .shapeinfo-container").on("click", ".corridorList .corridorEditor button", function (e) {
                if ($(this).attr("data-action") == "ok") {
                    var text = $(this).closest(".editor").find("input").val()
                    $(this).closest(".corridorList").find("span.corridor-title").html(text);
                    $(this).closest(".corridorList").addClass("modified");
                    $("#projectmap").trigger("changeModeOn");
                }
                that.clearEditCorridor();
            });



        },

        editSubCorridor: function (id) {
            this.clearEditSubcorridor();
            this.clearEditCorridor();

            this.$el.find(".corridorList ul li[data-id='" + id + "'] .subcorridor-wrapper").hide()

            // enter in edit mode
            var $editor = this.$el.find(".corridorList ul li[data-id='" + id + "'] .editor");
            $editor.removeClass("nodisplay");
            $editor.find("input").val($editor.closest("li").find("a").text());

            setTimeout(function () {
                $editor.find("input").select();
            }, 50);

            $("#projectmap").trigger("resetMode");

        },
        clearEditSubcorridor: function () {
            $("#projectmap").trigger("setMode", ["free"]);
            this.$el.find(".corridorList ul li .editor").addClass("nodisplay");
            this.$el.find(".corridorList .subcorridorItemContainer .subcorridor-wrapper").show();
            this.currentSubcorridor = undefined;
        },
        addSubcorridor: function (data, addTo) {
            this.clearEditSubcorridor();

            var template = Handlebars.compile(HTMLSubcorridorItem);
            var html = template(data);
            this.$el.find(".corridorList[data-id='" + addTo + "'] ul").append(html);
            this.addSubcorridorSortable();
            this.sortSubcorridor(data.tempId);
        },
        addCorridor: function (data) {

            var template = Handlebars.compile(HTMLCorridorItem);
            var html = template(data);
            this.$el.find(".shapeinfo-container .errorList").before(html);
            this.addSubcorridorSortable();
        },
        editCorridor: function (id) {
            this.clearEditSubcorridor();
            this.clearEditCorridor();

            this.$el.find(".corridorList[data-id='" + id + "'] .corridor-wrapper").hide();

            // enter in edit mode
            var $editor = this.$el.find(".corridorList[data-id='" + id + "'] .corridorEditor");
            $editor.removeClass("nodisplay");
            $editor.find("input").val($editor.closest(".corridorList").find("span.corridor-title").text());
            setTimeout(function () {
                $editor.find("input").select();
            }, 50);

            $("#projectmap").trigger("resetMode");
        },
        clearEditCorridor: function () {
            this.$el.find(".corridorList .corridor-wrapper").show();
            this.$el.find(".corridorList .editor").addClass("nodisplay");
        },
        addSubcorridorSortable: function () {
            //
            var that = this;
            $(".leaflet-infobar .generalinfo .shapeinfo-container .subcorridorItemContainer").sortable({
                connectWith: ".subcorridorItemContainer",
                handle: "i.sorter",
                axis: "y",
                placeholder: "subcorridorplaceholder",
                start: function (event, ui) {
                    $(ui.helper).addClass("modified");
                    $("#projectmap").trigger("resetMode");
                    $("#projectmap").trigger("changeModeOn");
                }
            }).disableSelection();



            $(".leaflet-infobar .generalinfo .shapeinfo-container .subcorridorItemContainer table tbody").sortable({
                axis: "y",
                start: function (event, ui) {
                    that.currentSortLink = $(this).find("tr").first().attr("data-leaflet");
                },
                stop: function (event, ui) {
                    var itemTbody = this;

                    setTimeout(function () {
                        if (that.sortSubcorridor($(itemTbody).closest("li").attr("data-id"))) {
                            var arr = that.getLayersFromLi($(itemTbody).closest("li"));
                            if (arr) {
                                var firstId = parseInt($(itemTbody).find("tr").first().attr("data-leaflet"));
                                if (arr.indexOf(firstId) >= 0) {
                                    arr.splice(arr.indexOf(firstId), 1);
                                    arr.unshift(firstId);
                                    $(itemTbody).closest("li").addClass("modified");
                                }
                            }
                        }

                    }, 100);

                    $("#projectmap").trigger("resetMode");
                    $("#projectmap").trigger("changeModeOn");

                }
            }).disableSelection();


        },
        updateIntegrityStatus: function (isError, itemCount) {
            $(".shapeinfo-container .integrityErrorOn").hide();
            $(".shapeinfo-container .integrityErrorOff").hide();

            if (itemCount > 0) {
                if (isError) {
                    $(".shapeinfo-container .integrityErrorOn").show();
                }
                else {
                    $(".shapeinfo-container .integrityErrorOff").show();
                }
            }


        },
        // show list of errors
        showIntegrityErrors: function (errorList) {
            var template = Handlebars.compile(HTMLTemplate_ErrorItem);
            var html = template({ errorData: errorList });
            this.$el.find(".errorList ul").html(html);
            this.$el.find(".errorList").show();

            //this.expandControl();
        },
        clearIntegrityErrors: function () {
            this.$el.find(".errorList").hide();
            this.$el.find(".errorList ul").html("");
        },
        // return the subcorridor temp id where layerid is in
        getSubcorridorIdFromLayerId: function (layerId) {

            var res = [];
            var that = this;
            this.$el.find(".corridorList ul li").each(function (nn, item) {

                var arr = that.getLayersFromLi($(this));
                if (arr) {
                    var index = arr.indexOf(layerId);
                    if (index > -1) {
                        res.push($(this).attr("data-id"));
                    }
                }
            });

            return res;

        },
        //add selected layer to current editable subcorridor
        //addSelectedLayer: function (id, tempId, updateCorridor, linkData) {


        //    var key = this.currentSubcorridor;
        //    if (tempId != undefined) {
        //        key = tempId;
        //    }
        //    if (key) {
        //        var arr = this.layersDictionary[key];
        //        if (!arr) {
        //            arr = new Array();
        //            this.layersDictionary[key] = arr;
        //        }
        //        arr.push(id);

        //        if (updateCorridor) {
        //            $("#projectmap").trigger("changeModeOn");
        //            this.$el.find(".corridorList ul li[data-id='" + key + "']").addClass("modified");

        //            var template = Handlebars.compile(HTMLSubcorridorLink);
        //            var html = template(linkData);
        //            this.$el.find(".corridorList ul li[data-id='" + key + "'] table tbody").append(html);
        //            this.sortSubcorridor(key);
        //        }
        //        else {
        //            var entityId = linkData;
        //            $(".corridorList td.link[data-value='" + entityId + "']").closest("tr").attr("data-leaflet", id);
        //        }
        //    }

        //},
        //remove selected layer from current editable subcorridor
        removeSelectedLayer: function (id, updateCorridor) {
            if (this.currentSubcorridor) {
                var arr = this.layersDictionary[this.currentSubcorridor];
                if (arr) {
                    var index = arr.indexOf(id);
                    if (index > -1) {
                        arr.splice(index, 1);
                        if (updateCorridor) {
                            $("#projectmap").trigger("changeModeOn");
                            this.$el.find(".corridorList ul li[data-id='" + this.currentSubcorridor + "']").addClass("modified");
                            this.$el.find(".corridorList li.selecting tr[data-leaflet='" + id + "']").remove();
                            this.sortSubcorridor(this.currentSubcorridor);
                        }
                    }

                }
            }
        },
        // update layer (link or nodes) on the corridor network
        updateSelectedLayer: function (linkData) {
            this.$el.find(".corridorList tr[data-leaflet='" + linkData.leaflet_id + "'] td.link span").html(linkData.link.name);

            this.$el.find(".corridorList tr[data-leaflet='" + linkData.leaflet_id + "'] td.link div.link").css("background-color", linkData.linkColor);


            if (linkData.nodeFrom) {
                this.$el.find(".corridorList td.node[data-value='" + linkData.nodeFrom.entityId + "'] img").attr("title", linkData.nodeFrom.name);
                this.$el.find(".corridorList td.node[data-value='" + linkData.nodeFrom.entityId + "'] img").attr("src", linkData.nodeFrom.img);
            }
            if (linkData.nodeTo) {
                this.$el.find(".corridorList td.node[data-value='" + linkData.nodeTo.entityId + "'] img").attr("title", linkData.nodeTo.name);
                this.$el.find(".corridorList td.node[data-value='" + linkData.nodeTo.entityId + "'] img").attr("src", linkData.nodeTo.img);
            }

        },
        sortSubcorridor: function (key) {

            //clear previous inverters
            this.$el.find(".corridorList ul li[data-id='" + key + "'] table tbody tr").removeClass("inverted");

            var that = this;
            var $first = this.$el.find(".corridorList ul li[data-id='" + key + "'] table tbody").find("tr").first();
            var linkCount = this.$el.find(".corridorList ul li[data-id='" + key + "'] table tbody tr").length;
            var fullSort = false;
            if ($first) {

                var inverter = function ($tr) {
                    $tr.addClass("inverted");
                    var $nodeStart = $tr.find("td.node.start").remove();
                    $nodeStart.removeClass("start").addClass("end");

                    var $nodeEnd = $tr.find("td.node.end").remove();
                    $nodeEnd.removeClass("end").addClass("start");

                    $tr.find("td.link").before($nodeEnd);
                    $tr.find("td.link").after($nodeStart);

                    if ($tr.find("td.link span").text().indexOf(" - ") >= 0) {
                        $tr.find("td.link span").html($nodeEnd.find("img").attr("title") + " - " + $nodeStart.find("img").attr("title"));
                    }

                }
                var iterator = function (pos, node) {
                    if (node) {

                        var $trs = that.$el.find(".corridorList ul li[data-id='" + key + "'] table tbody tr");
                        // search for start with node 'node'
                        var found = undefined;
                        for (var nn = pos + 1; nn < $trs.length; nn++) {
                            if (node == $trs.eq(nn).find("td.node.start img").attr("title")) {
                                found = $trs.eq(nn);
                                break;
                            }
                        }
                        if (!found) {
                            // search for end with node 'node'
                            for (var nn = pos + 1; nn < $trs.length; nn++) {
                                if (node == $trs.eq(nn).find("td.node.end img").attr("title")) {
                                    inverter($trs.eq(nn));
                                    found = $trs.eq(nn);
                                    break;
                                }
                            }
                        }
                        if (found) {
                            // swith pos
                            found.remove();
                            $trs.eq(pos).after(found);
                            if (linkCount <= pos + 2)
                                fullSort = true;
                            else
                                iterator(pos + 1, found.find("td.node.end img").attr("title"));
                        }
                        else {

                            if (pos == 0 && !$trs.eq(0).hasClass("inverted")) {
                                //try invert 0 and then sort
                                inverter($trs.eq(0));
                                iterator(0, $trs.eq(0).find("td.node.end img").attr("title"));
                            }
                            /*  no hace falta seguir ordenando si esta mal
                            else {
                                iterator(pos + 1, $trs.eq(pos + 1).find("td.node.end img").attr("title"));
                            }
                            */
                        }
                        $trs = null;
                    }
                };
            }

            iterator(0, $first.find("td.node.end img").attr("title"));
            $first.removeClass("inverted");

            if (!fullSort) {

                if (this.currentSortLink) {
                    var oldFirst = $first.closest("tbody").find("tr[data-leaflet='" + this.currentSortLink + "']").detach();
                    $first.closest("tbody").append(oldFirst);
                    $first.before(oldFirst);
                    this.currentSortLink = null;
                    this.sortSubcorridor(key);
                    return false;
                }
            }
            return true;
        },
        removeLayerFromMap: function (id) {
            this.$el.find(".corridorList tr[data-leaflet='" + id + "']").remove();
            var that = this;
            this.$el.find(".corridorList ul li").each(function (ii, item) {
                var arr = that.getLayersFromLi($(this));
                if (arr) {
                    var index = arr.indexOf(id);
                    if (index > -1) {
                        arr.splice(index, 1);
                        $(this).addClass("modified");
                    }
                }
            });

        },
        // return corridors and subcorridors data for save
        getCorridorsData: function (workLayer) {


            var res = {};
            var corridors = [];
            var that = this;
            $(".leaflet-infobar .generalinfo .shapeinfo-container .corridorList").each(function (nn, item) {

                if ($(this).hasClass("modified") || $(this).find(".subcorridorItemContainer li").hasClass("modified")) {

                    var corr = {
                        entityId: $(this).attr("data-entity-id"),
                        tempId: $(this).attr("data-id"),
                        name: $(this).find("span.corridor-title").text(),
                        childrens: []
                    };

                    $(this).find(".subcorridorItemContainer li").each(function (ii, item2) {

                        if ($(this).hasClass("modified")) {

                            var extraData = "";
                            var arr = that.getLayersFromLi($(this));
                            if (arr && arr.length > 0) {
                                // search for entityId
                                $.each(arr, function (ii, leaflet_id) {
                                    var layer = workLayer.getLayer(leaflet_id);
                                    if (layer && layer.options.entityId) {
                                        if (extraData != "")
                                            extraData += ",";
                                        extraData += layer.options.entityId;
                                    }
                                });
                                //end search
                            }

                            var firstEntityid = -1;
                            var firstGeoId = $(this).find("tr").first().attr("data-leaflet");
                            var layer = workLayer.getLayer(firstGeoId);
                            if (layer && layer.options.entityId) {
                                firstEntityid = layer.options.entityId
                            }


                            corr.childrens.push({
                                entityId: $(this).attr("data-entity-id"),
                                tempId: $(this).attr("data-id"),
                                name: $(this).find("a").text(),
                                isFree: false,
                                extraData: extraData,
                                childrens: [],
                                firstEntityid: firstEntityid,
                                firstGeoId: firstGeoId
                            });

                        }

                    });
                    corridors.push(corr);
                }


            });

            res.corridors = corridors;
            res.deletedCorridors = this.deletedCorridors;
            res.deletedSubcorridors = this.deletedSubcorridors;

            return res;
        },
        // set corridors and subcorridors data
        setCorridorData: function (corridors, skipClear) {
            var that = this;

            if (skipClear) {

                // add and update corridors / subcorridors
                $.each(corridors, function (ii, corridor) {

                    if (that.$el.find(".corridorList[data-entity-id='" + corridor.entityId + "']").length == 0) {
                        that.addCorridor(corridor);
                    }
                    else {
                        //update name
                        that.$el.find(".corridorList[data-entity-id='" + corridor.entityId + "'] span.corridor-title").html(corridor.name);
                        that.$el.find(".corridorList[data-entity-id='" + corridor.entityId + "']").attr("data-id", corridor.tempId);
                    }


                    $.each(corridor.childrens, function (nn, subcorridor) {
                        if (that.$el.find(".corridorList .subcorridorItemContainer li[data-entity-id='" + subcorridor.entityId + "']").length == 0) {
                            that.addSubcorridor(subcorridor, corridor.tempId);
                        }
                        else {
                            //update name
                            that.$el.find(".corridorList .subcorridorItemContainer li[data-entity-id='" + subcorridor.entityId + "'] a.subcorridor").html(subcorridor.name);
                        }
                    });
                });

                //delete old corridors / subcorridors
                this.$el.find(".corridorList").each(function (ii, item) {
                    if ($(item).attr("data-entity-id")) {
                        var corr_id = $(item).attr("data-entity-id");
                        var found;
                        for (var nn = 0; nn < corridors.length; nn++) {
                            if (corridors[nn].entityId == corr_id) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            $(item).remove();
                        }
                    }
                });

                this.$el.find(".corridorList .subcorridorItemContainer li").each(function (ii, item) {
                    if ($(item).attr("data-entity-id")) {
                        var subcorr_id = $(item).attr("data-entity-id");
                        var found;
                        for (var nn = 0; nn < corridors.length; nn++) {
                            for (var jj = 0; jj < corridors[nn].childrens.length; jj++) {
                                if (corridors[nn].childrens[jj].entityId == subcorr_id) {
                                    found = true;
                                    break;
                                }
                            }
                        }
                        if (!found) {
                            $(item).remove();
                        }
                    }
                });

            }
            else {
                this.clearContent();

                var template = Handlebars.compile(HTMLCorridorFull);
                var html = template(corridors);
                this.$el.find(".shapeinfo-container .errorList").before(html);
                this.addSubcorridorSortable();

            }




            // Show assign demand button
            $(".leaflet-infobar .generalinfo button[data-rel='assign_demand_costs']").show();
        },
        // update id's generated in save
        updateCorridorData: function (data) {
            var that = this;
            $.each(data.corridors, function (ii, corridor) {

                that.$el.find(".corridorList[data-id='" + corridor.tempId + "']").attr("data-entity-id", corridor.entityId);
                $.each(corridor.childrens, function (nn, subcorridor) {
                    that.$el.find(".corridorList .subcorridorItemContainer li[data-id='" + subcorridor.tempId + "']").attr("data-entity-id", subcorridor.entityId);
                });

            });

            $.each(data.geometries, function (ii, geo) {
                if (geo.geometryType == 1) { //node
                    $(".leaflet-infobar .generalinfo .subcorridorItemContainer li table td.node[data-leaflet='" + geo.geometryId + "']").attr("data-value", geo.entityId);
                }
                else { //link
                    $(".leaflet-infobar .generalinfo .subcorridorItemContainer li table td.link[data-leaflet='" + geo.geometryId + "']").attr("data-value", geo.entityId);
                }
            });

            this.deletedCorridors = [];
            this.deletedSubcorridors = [];
            this.$el.find(".corridorList").removeClass("modified");
            this.$el.find(".corridorList ul li").removeClass("modified");


        },
        clearContent: function () {
            this.$el.find(".corridorList").remove();
        },
        // return array of leaflet id's of links in subccorridor
        getLinksIdsInSubCorridor: function (id) {
            var $li = this.$el.find(".corridorList ul li[data-entity-id='" + id + "']");
            if ($li) {
                return this.getLayersFromLi($li);
            }
        },
        updateHasChanges: function (hasChanges) {
            if (hasChanges) {
                $(".leaflet-infobar .generalinfo button[data-rel='save']").addClass("btn-red");
            }
            else {
                $(".leaflet-infobar .generalinfo button[data-rel='save']").removeClass("btn-red");
            }
        },
        updateMode: function (mode) {
            if (mode != "selectLinks") {
                $(".leaflet-infobar .generalinfo .subcorridorItemContainer li").removeClass("selecting");

            }
        },
        clearContent: function () {
            $(".leaflet-infobar .generalinfo .errorList").hide();
            $(".leaflet-infobar .generalinfo .integrityErrorOn").hide();
            $(".leaflet-infobar .generalinfo .corridorList").remove();
            $(".leaflet-infobar project-title").html("");
        },
        markWithData: function (dataInFPCase) {
            var that = this;

            $.each(dataInFPCase.links, function (ii, item) {
                that.$el.find(".shapeinfo-container table td[data-value='" + item + "'] span").removeClass("nodata");
            });
            $.each(dataInFPCase.nodes, function (ii, item) {
                that.$el.find(".shapeinfo-container table td[data-value='" + item + "'] img").removeClass("nodata");
            });

        },
        highlightLinks: function (arr) {
            this.$el.find(".subcorridorItemContainer table tr").removeClass("selected");
            this.$el.find(".subcorridorItemContainer a.subcorridor").removeClass("selected");

            if (arr) {
                var that = this;

                $.each(arr, function (nn, leaflet_id) {
                    that.$el.find(".subcorridorItemContainer table tr[data-leaflet='" + leaflet_id + "']").addClass("selected");

                    //mark subcorridor
                    that.$el.find(".subcorridorItemContainer li").each(function (ii, item) {
                        var arr = that.getLayersFromLi($(item));
                        if (arr && arr.indexOf(leaflet_id) >= 0) {
                            $(item).find("a.subcorridor").addClass("selected");
                        }
                    });
                });
            }
        },
        getLayersFromLi: function ($li) {
            return this.layersDictionary[$li.attr("data-id")];
        }
    });
    return view;
});